package mcom.xmks.bluetooth.mesh.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;

import mcom.xmks.bluetooth.mesh.dialog.DialogUtil;
import mcom.xmks.bluetooth.mesh.dialog.InputShareFileInfoDialog;
import mcom.xmks.bluetooth.mesh.ota.ShareFileResolver;
import mcom.xmks.bluetooth.mesh.utils.LogTool;

public abstract class NodeMainActivity extends NodeBaseActivity{
    protected void checkShareFile(){
        Intent intent=getIntent();
        if(intent!=null){
            Uri uri=intent.getData();
            if(uri!=null){
                LogTool.d(String.format("we receive share file:", uri));
                String lastPathSegment=uri.getLastPathSegment();
                if(lastPathSegment!=null && lastPathSegment.length()>4 &&
                        (lastPathSegment.endsWith(".bin")||
                                lastPathSegment.endsWith(".BIN")||
                                lastPathSegment.endsWith(".hex")||
                                lastPathSegment.endsWith(".HEX"))){
                    showShareFileDialog(lastPathSegment,uri);
                }else{
                    showToast("只接收bin或者hex格式的文件");
                }
            }
        }
    }
    protected void showShareFileDialog(String filename,Uri uri){
         InputShareFileInfoDialog dialog=InputShareFileInfoDialog.getInstance(filename);
        dialog.setCancelable(false);
        dialog.setListener(name -> {
            saveShareFileToPrivateFolder(this,uri,name);
        });
    }
    private void saveShareFileToPrivateFolder(Context context,Uri uri,String fileName){
        try {
            DialogUtil.getInstance().showLoadingDialog((Activity) context,"保存文件");
            ShareFileResolver.uriToFile(context,uri,fileName);
            DialogUtil.getInstance().hideLoadingDialog();
            showToast("保存升级文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            DialogUtil.getInstance().hideLoadingDialog();
            showToast(e.getMessage());
        }
    }
}
